package com.wx.spring.mvc;

import com.wx.spring.annotations.MyController;
import com.wx.spring.annotations.MyRequestMapping;
import com.wx.spring.exception.SpringMvcException;
import com.wx.spring.utils.AnnotationUtils;
import com.wx.spring.utils.VesselUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName Handler
 * @Author wx
 * @Description 处理器
 * @Date 2019-01-30-18:10
 */
public class Handler {
    /**
     * @methodName: bindingRequestMapping
     * @author: wx
     * @description: 绑定路径与方法
     * @param beanContainerMap
     * @date: 2019/1/30
     * @return: java.util.Map<java.lang.String,java.lang.reflect.Method>
     */
    public static Map<String, Method> bindingRequestMapping(Map<String, Object> beanContainerMap){
        Map<String, Method> handlerMapping = new HashMap<>();
        if (beanContainerMap != null && !beanContainerMap.isEmpty()){
            beanContainerMap.forEach((k,v)->{
                Class aClass = v.getClass();
                Annotation annotation = aClass.getAnnotation(MyController.class);
                //获取所有的方法
                Method[] methods = aClass.getMethods();
                if (AnnotationUtils.isNotEmpty(annotation) && VesselUtils.isNotArrayEmpty(methods)){
                    for (Method method : methods) {
                        MyRequestMapping requestMappingAnnotation = method.getAnnotation(MyRequestMapping.class);
                        if (AnnotationUtils.isNotEmpty(requestMappingAnnotation)){
                            String key = requestMappingAnnotation.value();
                            handlerMapping.put(key,method);
                        }
                    }
                }
            });
        }
        else{
            throw new SpringMvcException("实例化bean异常，没有找到容器");
        }

        return handlerMapping;

    }
}
